package com.ruoyi.web.controller.comlbs;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ruoyi.common.config.BigDataConfig;
import com.ruoyi.common.config.FtpConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.Page;
import com.ruoyi.common.enums.comlbs.VehicleStatusEnum;
import com.ruoyi.common.exception.BigDataException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.BigDataResponse;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.DriverInfo;
import com.ruoyi.system.domain.request.reportstatistics.*;
import com.ruoyi.system.domain.vo.reportstatistics.*;
import com.ruoyi.system.service.IReportStatisticsService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.utils.ComLbsUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述 报表统计Controller
 * 作者 ZhangPing
 * 创建时间 2023/8/17 15:17
 */
@RestController
@RequestMapping("/comlbs/reportStatistics")
public class ReportStatisticsController extends BaseController {

    @Autowired
    private BigDataConfig bigDataConfig;
    @Autowired
    private FtpConfig ftpConfig;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IReportStatisticsService reportStatisticsService;

    @ApiOperation("多媒体数据列表")
    @PostMapping("/photo/list")
    public AjaxResult queryPage(@Validated ReportStatisticsListParam param) {
        return success(reportStatisticsService.photoList(param));
    }

    @ApiOperation("设备里程统计")
    @PostMapping("/deviceMileage/list")
    public AjaxResult deviceMileageList(@Validated ReportStatisticsListParam param) {
        return success(reportStatisticsService.deviceMileageList(param, false));
    }

    @ApiOperation("设备里程统计导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/deviceMileage/listExport")
    public void deviceMileageListExport(@Validated ReportStatisticsListParam param, HttpServletResponse response) {
        Page<MileageStatistics> page = reportStatisticsService.deviceMileageList(param, true);
        new ExcelUtil<>(MileageStatistics.class).exportExcel(response, page.getList(), "设备里程统计");
    }

    @ApiOperation("设备里程统计汇总导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/deviceMileage/listSummaryExport")
    public void deviceMileageListSummaryExport(@Validated ReportStatisticsListParam param, HttpServletResponse response) {
        List<MileageStatistics> resultList = reportStatisticsService.deviceMileageListSummaryExport(param);
        ExcelUtil<MileageStatistics> util = new ExcelUtil<MileageStatistics>(MileageStatistics.class);
        util.hideColumn("day");
        util.exportExcel(response, resultList,
                String.format("设备里程统计汇总(%s至%s)", param.getStartTime().split(" ")[0], param.getEndTime()).split(" ")[0]);
    }

    @ApiOperation("设备里程明细")
    @PostMapping("/deviceMileage/detailList")
    public AjaxResult deviceMileageDetailList(@Validated ReportStatisticsListParam param) {
        return success(reportStatisticsService.deviceMileageDetailList(param, false));
    }

    @ApiOperation("设备里程明细导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize", "dvo"})
    @PostMapping("/deviceMileage/detailListExport")
    public void deviceMileageDetailListExport(@Validated ReportStatisticsListParam param, HttpServletResponse response) {
        Page<MileageStatistics> page = reportStatisticsService.deviceMileageDetailList(param, true);
        new ExcelUtil<>(MileageStatistics.class).exportExcel(response, page.getList(), "设备里程明细");
    }

    @ApiOperation("历史轨迹明细")
    @PostMapping("/trajectory/historyList")
    public AjaxResult trajectoryHistoryList(@Validated TrajectoryParam param) {
        return success(reportStatisticsService.trajectoryHistoryList(param, false));
    }

    @ApiOperation("历史轨迹明细导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/trajectory/historyListExport")
    public void trajectoryHistoryListExport(@Validated TrajectoryParam param, HttpServletResponse response) {
        Page<Trajectory> page = reportStatisticsService.trajectoryHistoryList(param, true);
        new ExcelUtil<>(Trajectory.class).exportExcel(response, page.getList(), "历史轨迹明细");
    }

    @ApiOperation("设备上线统计")
    @PostMapping("/deviceOnline/list")
    public AjaxResult deviceOnlineList(@Validated ReportStatisticsListParam param) {
        return success(reportStatisticsService.deviceOnlineList(param, false));
    }

    @ApiOperation("设备上线统计导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/deviceOnline/listExport")
    public void deviceOnlineListExport(@Validated ReportStatisticsListParam param, HttpServletResponse response) {
        Page<DeviceOnline> page = reportStatisticsService.deviceOnlineList(param, true);
        new ExcelUtil<>(DeviceOnline.class).exportExcel(response, page.getList(), "设备上线统计");
    }

    @ApiOperation("报警统计")
    @PostMapping("/deviceAlarm/list")
    public AjaxResult deviceAlarmList(@Validated DeviceAlarmListParam param) {
        return success(reportStatisticsService.deviceAlarmList(param, false));
    }

    @ApiOperation("报警统计导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/deviceAlarm/listExport")
    public void deviceAlarmListExport(@Validated DeviceAlarmListParam param, HttpServletResponse response) {
        Page<AlarmStatistics> page = reportStatisticsService.deviceAlarmList(param, true);
        new ExcelUtil<>(AlarmStatistics.class).exportExcel(response, page.getList(), "报警统计");
    }

    @ApiOperation("报警明细")
    @PostMapping("/deviceAlarm/detailList")
    public AjaxResult deviceAlarmDetailList(@Validated DeviceAlarmListParam param) {
        return success(reportStatisticsService.deviceAlarmDetailList(param, false));
    }

    @ApiOperation("报警明细导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/deviceAlarm/detailListExport")
    public void deviceAlarmDetailListExport(@Validated DeviceAlarmListParam param, HttpServletResponse response) {
        Page<AlarmDetail> page = reportStatisticsService.deviceAlarmDetailList(param, true);
        new ExcelUtil<>(AlarmDetail.class).exportExcel(response, page.getList(), "报警明细");
    }

    @ApiOperation("报警证据")
    @PostMapping("/deviceAlarm/evidence")
    public AjaxResult deviceAlarmEvidence(@RequestParam String alarmCode) {
        //远程调用接口
        BigDataResponse<List<JSONObject>> response = HttpRequest.getBigDataNoEncode(bigDataConfig.getApiUrl() + "/adasAlarm/queryOneByAmc",
                new JSONObjectPro().put("alarmcode", alarmCode), new TypeReference<List<JSONObject>>(){}.getType());
        if (!response.isSuccess()) throw new BigDataException();
//        List<JSONObject> dataItems = response.getData();
        List<JSONObject> dataItems = new ArrayList<>();
        dataItems.forEach(x -> x.put("pth", x.get("pth") == null ? null : ftpConfig.ftp2Http(x.getString("pth"))));
        return success(dataItems);
    }

    @ApiOperation("公司整点上线率")
    @PostMapping("/deviceOnline/companyHourlyOnlineRate")
    public AjaxResult companyHourlyOnlineRate(@Validated CompanyHourlyOnlineRateParam param) {
        return success(reportStatisticsService.companyHourlyOnlineRate(param, false));
    }

    @ApiOperation("公司整点上线率导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/deviceOnline/companyHourlyOnlineRateExport")
    public void companyHourlyOnlineRateExport(@Validated CompanyHourlyOnlineRateParam param, HttpServletResponse response) {
        Page<CompanyHourlyOnlineRate> page = reportStatisticsService.companyHourlyOnlineRate(param, true);
        new ExcelUtil<>(CompanyHourlyOnlineRate.class).exportExcel(response, page.getList(), "公司整点上线率");
    }

    @ApiOperation("公司整点上线率汇总导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize", "companyId"})
    @PostMapping("/deviceOnline/companyHourlyOnlineRateSummaryExport")
    public void companyHourlyOnlineRateSummaryExport(@Validated CompanyHourlyOnlineRateParam param, HttpServletResponse response) {
        List<CompanyHourlyOnlineRateSummary> list = reportStatisticsService.companyHourlyOnlineRateSummaryExport(param);
        String dateRange = "(" + param.getStartTime().split(" ")[0] + "至" + param.getEndTime().split(" ")[0] + ")";
        new ExcelUtil<>(CompanyHourlyOnlineRateSummary.class).exportExcel(response, list, "公司整点上线率汇总" + dateRange);
    }

    @ApiOperation("公司整点上线详情")
    @PostMapping("/deviceOnline/companyHourlyOnlineDetail")
    public AjaxResult companyHourlyOnlineDetail(@Validated CompanyHourlyOnlineDetailParam param) {
        return success(reportStatisticsService.companyHourlyOnlineDetail(param));
    }

    @ApiOperation("公司整点上线详情导出")
    @PostMapping("/deviceOnline/companyHourlyOnlineDetailExport")
    public void companyHourlyOnlineDetailExport(@Validated CompanyHourlyOnlineDetailParam param, HttpServletResponse response) {
        List<CompanyHourlyOnlineDetail> resultList = reportStatisticsService.companyHourlyOnlineDetail(param);
        new ExcelUtil<>(CompanyHourlyOnlineDetail.class).exportExcel(response, resultList, "公司整点上线详情");
    }

    @ApiOperation("设备状态统计数量")
    @PostMapping("/deviceStatus/statisticsCount")
    public AjaxResult deviceStatusStatisticsCount() {

        //远程调用接口
        BigDataResponse response = HttpRequest.getBigDataNoEncode(bigDataConfig.getApiUrl() + "/dws/device/status/sta",  new JSONObjectPro(), JSONObject.class);
        if (!response.isSuccess()) throw new BigDataException();

        // 提取分页数据
        BigDataResponse.PageData<JSONObject> pageData = response.getData();
        List<JSONObject> dataItems = pageData.getDataItems();

        // 处理空数据
        if (ObjectUtils.isEmpty(dataItems)) {
            return success();
        }

        JSONObjectPro result = new JSONObjectPro()
            .put("netCar", dataItems.get(0).getIntValue("totalNum"))
            .put("onlineCar", dataItems.get(0).getIntValue("onlineNum"))
            .put("offlineCar", dataItems.get(0).getIntValue("offlineNum"))
            .put("neverOnlineCar", dataItems.get(0).getIntValue("neverNum"))
            .put("seventyNotOnlineCar", dataItems.get(0).getIntValue("sevenDayNum"))
            .put("thirtyNotOnlineCar", dataItems.get(0).getIntValue("thirtyDayNum"));

        return success(result);
    }

    @ApiOperation("设备状态统计列表")
    @PostMapping("/deviceStatus/statisticsList")
    private AjaxResult deviceStatusStatisticsList(@Validated StatusStatisticsListParam param) {
        return success(reportStatisticsService.deviceStatusStatisticsList(param, false));
    }

    @ApiOperation("设备状态统计列表导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/deviceStatus/statisticsListExport")
    private void deviceStatusStatisticsListExport(@Validated StatusStatisticsListParam param, HttpServletResponse response) {
        Page<DeviceStatusStatistics> page = reportStatisticsService.deviceStatusStatisticsList(param, true);
        new ExcelUtil<>(DeviceStatusStatistics.class).exportExcel(response, page.getList(), "设备状态统计列表");
    }

    @ApiOperation("人脸识别统计列表")
    @PostMapping("/personFaceResult/list")
    public AjaxResult personFaceResultList(@RequestBody PersonFaceParam param) {
        return success(reportStatisticsService.personFaceResultList(param, false));
    }

    @ApiOperation("人脸识别统计导出")
    @ApiOperationSupport(ignoreParameters = {"pageNum", "pageSize"})
    @PostMapping("/personFaceResult/listExport")
    public void personFaceResultListExport(PersonFaceParam param, HttpServletResponse response) {
        Page<PersonFaceResultStatistics> page = reportStatisticsService.personFaceResultList(param, true);
        new ExcelUtil<>(PersonFaceResultStatistics.class).exportExcel(response, page.getList(), "人脸识别统计");
    }
}
